package com.duan.laugh.email.config;

import com.duan.laugh.common.core.util.R;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.CollectionUtils;
import org.springframework.validation.BindException;
import org.springframework.validation.FieldError;
import org.springframework.web.bind.MethodArgumentNotValidException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

import java.util.List;
import java.util.StringJoiner;

/**
 * <p>
 * 全局参数校验异常处理
 * </p>
 *
 * @author liutf
 * @since 2019-10-31
 */
@RestControllerAdvice
@Slf4j
public class ValidateExceptionHandler {

    @ExceptionHandler(value = {Exception.class})
    public R handleBindException(Exception ex) {
        log.error("{}", ex);
        StringJoiner stringJoiner = new StringJoiner(",");
        if (ex instanceof BindException) {
            // 非请求body参数，例如@RequestParam接收的
            List<FieldError> fieldErrorList = ((BindException) ex).getFieldErrors();
            if (!CollectionUtils.isEmpty(fieldErrorList)) {
                for (FieldError fieldError : fieldErrorList) {
                    if (fieldError != null && fieldError.getDefaultMessage() != null) {
                        stringJoiner.add(fieldError.getDefaultMessage());
                    }
                }
            }
        } else if (ex instanceof MethodArgumentNotValidException) {
            // 请求body里面的参数，例如@RequestBody接收的
            List<FieldError> fieldErrorList = ((MethodArgumentNotValidException) ex).getBindingResult().getFieldErrors();
            if (!CollectionUtils.isEmpty(fieldErrorList)) {
                for (FieldError fieldError : fieldErrorList) {
                    if (fieldError != null && fieldError.getDefaultMessage() != null) {
                        stringJoiner.add(fieldError.getDefaultMessage());
                    }
                }
            }
        } else {
            // 其他异常处理
            return R.failed(ex.getMessage());
        }
        // 生成返回结果
        return R.failed(stringJoiner.toString());
    }
}
